package com.bestv.handler;

import com.bestv.db.DbFactory;
import com.bestv.db.DbHelper;
import com.bestv.db.MysqlDb;
import com.bestv.util.DbConstant;
import org.apache.log4j.Logger;

import java.sql.*;

/**
 * Created by charle-chen on 15/11/25.
 */
public class UpdateTopKeywordThread extends Thread {
    private int limit;
    private int start;
    private Logger logger = Logger.getLogger(getClass());

    @Override
    public void run() {
        try {
            MysqlDb mysqlDb = (MysqlDb)DbFactory.getDbInstance(DbConstant.MYSQL_DB);
            String sql = "select keyword,py,id from top_keyword where count>0 limit " + start + "," + limit;
            Statement st = mysqlDb.getConn().createStatement();
            ResultSet rs = st.executeQuery(sql);
            while (rs.next()) {
                String query_sql = "select count(1) as num from info where name like " + "'%" + rs.getString("keyword") + "%'"
                        + " and name_py like " + "'%" + rs.getString("py") + "%'" + " and update_flag<>2";
                Statement querySt = mysqlDb.getConn().createStatement();
                ResultSet tempRs = querySt.executeQuery(query_sql);
                while (tempRs.next()) {
                    if (tempRs.getInt("num") == 0) {
                        String update_sql = "update top_keyword set count=0 where id=" + rs.getInt("id");
                        mysqlDb.getConn().createStatement().executeUpdate(update_sql);
                        logger.info(Thread.currentThread().getName() + ": update the keyword " + rs.getString("keyword") + " success");
                    }
                }
                tempRs.close();
                querySt.close();
            }
            rs.close();
            st.close();
            DbHelper.closeDb(mysqlDb);
            logger.info(Thread.currentThread().getName() + ": update top_keyword table finished");
        } catch (SQLException e) {
            logger.error("update topkeyword sql error");
            e.printStackTrace();
        }
    }

    public void setLimit(int limit) {
        this.limit = limit;
    }

    public void setStart(int start) {
        this.start = start;
    }
}


